package com.suma.android.update;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;

import com.suma.android.activity.R;
import com.suma.android.constant.Constant;

public class UpdateManager {
	// 主窗体
	private Context context;
	// 进度条
	private ProgressDialog progress;
	// 后台版本校验
	private CheckUpdateTask checkUpdateTask;
	// 后台下载
	private DownloadTask downloadTask;

	public UpdateManager(Context context) {
		this.context = context;
	}

	public void update() {
		checkUpdateTask = new CheckUpdateTask();
		checkUpdateTask.execute();
	}

	private class CheckUpdateTask extends AsyncTask<Void, Void, Boolean> {
		private String versionName;
		private String desc;
		private String apkName;
		private String download;

		@Override
		protected Boolean doInBackground(Void... params) {
			// 校验版本号是否需要升级，需要升级checkUpdate则为true，否则checkUpdate为false
			Boolean checkUpdate = false;
			try {
				HttpGet httpget = new HttpGet(Constant.CHECK_UPDATE_URL);
				HttpClient client = new DefaultHttpClient();
				HttpResponse response = client.execute(httpget);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					String msg = EntityUtils.toString(response.getEntity(),"utf-8");
					JSONArray json = new JSONArray(msg);
					String versionCode = json.getJSONObject(0).getString(
							"versionCode");
					versionName = json.getJSONObject(0)
							.getString("versionName");
					desc = json.getJSONObject(0).getString("desc");
					apkName = json.getJSONObject(0).getString("apkName");
					download = json.getJSONObject(0).getString("download");
					int newversion = Integer.valueOf(versionCode);
					int curversion = context.getPackageManager()
							.getPackageInfo(Constant.PACKAGE_NAME, 0).versionCode;
					if (curversion < newversion) {
						checkUpdate = true;
					}
					// 保存上次校验升级时间
					SharedPreferences sp = context.getSharedPreferences(
							Constant.SHARE_PREF_NAME, Context.MODE_PRIVATE);
					sp.edit().putLong(Constant.CHECK_VERSION_KEY,
							System.currentTimeMillis()).commit();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return checkUpdate;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result != null && result == true) {				
				// 弹出是否安装对话框
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				String msg = context.getString(R.string.info_newversion)
						+ versionName + "\n" + desc;
				builder.setTitle(R.string.title_update)
						.setMessage(msg)
						.setCancelable(false)
						.setPositiveButton(R.string.confirm_update,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// 弹出进度条
										showProgress();
										// 下载安装文件
										downloadTask = new DownloadTask();
										downloadTask.execute(download, apkName);
									}
								})
						.setNegativeButton(R.string.cancle_update,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
			}
			super.onPostExecute(result);
		}

	}

	private void showProgress() {
		progress = new ProgressDialog(context);
		progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progress.setMax(100);
		progress.setTitle(R.string.title_update);
		progress.setCancelable(false);
		progress.setMessage(context.getString(R.string.title_downing));
		progress.setButton(DialogInterface.BUTTON_NEGATIVE,
				context.getString(R.string.cancle),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						progress.dismiss();
						checkUpdateTask.cancel(true);
					}
				});
		progress.show();
	}

	private class DownloadTask extends AsyncTask<String, Integer, Boolean> {
		private File apkfile;

		@Override
		protected Boolean doInBackground(String... params) {
			String path = params[0];
			String fileName = params[1];
			Boolean result = false;

			HttpURLConnection urlConnection = null;
			FileOutputStream fileOutput = null;
			try {
				URL url = new URL(path);
				urlConnection = (HttpURLConnection) url.openConnection();
				urlConnection.setRequestMethod("GET");
				urlConnection.setDoOutput(true);
				urlConnection.connect();

				String directory = Environment.getExternalStorageDirectory()
						+ "/Download/";
				apkfile = new File(directory, fileName);
				fileOutput = new FileOutputStream(apkfile);
				InputStream inputStream = urlConnection.getInputStream();
				int totalSize = urlConnection.getContentLength();
				int downloadedSize = 0;

				byte[] buffer = new byte[1024];
				int bufferLength = 0;
				while ((bufferLength = inputStream.read(buffer)) > 0) {
					fileOutput.write(buffer, 0, bufferLength);
					downloadedSize += bufferLength;
					publishProgress(100 * (downloadedSize / totalSize));
				}
				result = true;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (urlConnection != null) {
						urlConnection.disconnect();
					}
					if (fileOutput != null) {
						fileOutput.close();
					}
				} catch (Exception ex) {
				}
			}
			return result;
		}

		@Override
		protected void onCancelled() {
			if (apkfile != null && apkfile.exists()) {
				apkfile.delete();
			}
			super.onCancelled();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			progress.setProgress(values[0]);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			progress.dismiss();
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(apkfile),
					"application/vnd.android.package-archive");
			context.startActivity(intent);
			super.onPostExecute(result);
		}

	}

}
